package com.qiantu.phone.ui.fragment;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.heytap.mcssdk.utils.LogUtil;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseDialog;
import com.hjq.base.FragmentPagerAdapter;
import com.hjq.http.listener.HttpCallback;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.TitleBarFragment;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.iconswitch.IconSwitch;
import com.qiantu.phone.ui.activity.AddRoomActivity;
import com.qiantu.phone.ui.activity.FloorSortActivity;
import com.qiantu.phone.ui.activity.RoomSrotActivity;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.dialog.OptionDialog;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.widget.ViewPagerScrollIndicator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

public class RoomFragment extends TitleBarFragment<AppActivity> {
    private List<String> floorTitles = new ArrayList<>();
    private ViewPagerScrollIndicator tabBar;
    private View btnAdd;
    private View btnSetting;
    private IconSwitch iconSwitch;
    private ViewPager viewPager;
    private int currentItem;
    private List<FloorBean> floors = new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();
    private BottomEditDialog mBottomEditDialog;
    private FloorListFragment floorListFragment;

    int showType = 0;

    Boolean hideSettingBtn = false;

    FragmentPagerAdapter<Fragment> mPagerAdapter;

    public RoomFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if(savedInstanceState != null){
            currentItem = savedInstanceState.getInt("currentItem", 0);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_room;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        tabBar = findViewById(R.id.tab_bar);
        btnAdd = findViewById(R.id.btn_add);
        iconSwitch = findViewById(R.id.icon_switch);
        btnSetting = findViewById(R.id.room_setting);
        viewPager = findViewById(R.id.view_pager);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        setOnClickListener(btnAdd,btnSetting);
        iconSwitch.setCheckedChangeListener(new IconSwitch.CheckedChangeListener() {
            @Override
            public void onCheckChanged(IconSwitch.Checked current) {
                showType = current == IconSwitch.Checked.LEFT ? 0 : 1;
                changeShowType();
            }
        });
    }
    private void initViewPager() {
        List<Fragment> oldFragments = new ArrayList<>();
        for(Fragment fragment : fragments){
            oldFragments.add(fragment);
        }
        fragments.clear();
        mPagerAdapter = new FragmentPagerAdapter<>(this);
        fragments = new ArrayList<>();
        floorTitles.clear();
        if(floors.get(0).getType() != 1){
            if(floorListFragment == null){
                floorListFragment = FloorListFragment.newInstance(showType);
            }
            floorTitles.add("空间");
            fragments.add(floorListFragment);
            mPagerAdapter.addFragment(floorListFragment);
        }
        for (int i = 0; i < floors.size(); i++) {
            FloorBean floorBean = floors.get(i);
            floorTitles.add(floorBean.getFloorName());
            RoomListFragment fragment = getHasExistFragment(oldFragments, floorBean.getFloorSerialNo(), showType);
            if(fragment == null){
                fragment = RoomListFragment.newInstance(floorBean.getFloorSerialNo(), showType);
            }
            fragments.add(fragment);
            mPagerAdapter.addFragment(fragment);
        }
        oldFragments.clear();
        viewPager.setAdapter(mPagerAdapter);
        tabBar.setupViewpager(viewPager);
        tabBar.setTitleList(floorTitles);

        if(tabBar.getCurrentItem() >= floorTitles.size()){
            tabBar.selectTab(floorTitles.size() - 1);
        }
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2 || hideSettingBtn){
            btnSetting.setVisibility(View.GONE);
        }else{
            btnSetting.setVisibility(View.VISIBLE);
        }
        iconSwitch.setChecked(showType == 0 ? IconSwitch.Checked.LEFT : IconSwitch.Checked.RIGHT);
        changeShowType();
    }

    private RoomListFragment getHasExistFragment(List<Fragment> fragments, String floorSerialNo, int type){
        for(Fragment fragment : fragments){
            if(fragment instanceof RoomListFragment){
                RoomListFragment homeSubFragment = (RoomListFragment) fragment;
                if(floorSerialNo != null && floorSerialNo.equals(homeSubFragment.getFloorSerialNo())){
                    return homeSubFragment;
                }
            }
        }
        return null;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        if(viewPager != null){
            outState.putInt("currentItem", viewPager.getCurrentItem());
        }
    }

    @Override
    protected void initData() {
        floors = LLFloorDBManager.getInstance(getContext()).getFloorByHouseSerialNo(AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo());
        if(floors.size() == 1 && floors.get(0).getType() == 1){
            floors.get(0).setFloorName(getString(R.string.room));
            List rooms = LLRoomDBManager.getInstance(getContext()).getRoomByFloorSerialNo(floors.get(0).getFloorSerialNo());
            hideSettingBtn = rooms.size() < 2;
        }else{
            for(FloorBean floorBean : floors){
                if(floorBean.getType() == 1){
                    floors.remove(floorBean);
                    break;
                }
            }
            hideSettingBtn = false;
        }
        initViewPager();
    }

    public ViewPager getViewPager() {
        return viewPager;
    }

    @Override
    public void onClick(View view) {
        if (view == btnAdd){
            FloorBean floorBean;
            if(tabBar.titles.size() == 1){
                floorBean = floors.get(0);
            }if(tabBar.getCurrentItem() == 0){
                floorBean = floors.get(tabBar.getCurrentItem());
            }else{
                floorBean = floors.get(tabBar.getCurrentItem() - 1);
            }
            gotoAddRoomActivity(floorBean.getFloorSerialNo());
        }else if(view == btnSetting){
            showEditFloorDialog(btnSetting);
        }
    }

    private void gotoAddRoomActivity(String floorSerialNo){
        Intent intent = new Intent(getContext(), AddRoomActivity.class);
        intent.putExtra("floorSerialNo", floorSerialNo);
        startActivity(intent);
    }

    public void  setFirstShowType(int showType){
        this.showType = showType;
    }

    private void changeShowType(){
        if(floorListFragment != null){
            floorListFragment.changeShowType(showType);
        }
        for(Fragment fragment : fragments) {
            if (fragment instanceof RoomListFragment) {
                if(((RoomListFragment) fragment).getFloorSerialNo() != null){
                    RoomListFragment homeSubFragment = (RoomListFragment) fragment;
                    homeSubFragment.changeShowType(showType);
                }
            }
        }
    }

    private OptionDialog optionDialog;
    private void showEditFloorDialog(View atView) {
        if (optionDialog == null) {
            optionDialog = new OptionDialog(getContext());
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(getResources().getDimensionPixelSize(R.dimen.dp_6))
                    .asCustom(optionDialog);
        }
        List<OptionDialog.Option> options = new ArrayList<>();
        FloorBean floorBean;
        if(tabBar.titles.size() == 1){
            floorBean = floors.get(0);
            options.add(new OptionDialog.Option(R.attr.icon_intelligent_sort, "房间排序"));
        }else if(tabBar.getCurrentItem() == 0){
            floorBean = floors.get(0);
            options.add(new OptionDialog.Option(R.attr.icon_intelligent_sort, "楼层排序"));
        }else{
            floorBean = floors.get(tabBar.getCurrentItem() - 1);
            RoomListFragment fragment = (RoomListFragment) fragments.get(tabBar.getCurrentItem());
            options.add(new OptionDialog.Option(R.attr.icon_navigationbar_edit_black, "修改名称"));
            if(fragment.rooms.size() > 1){
                options.add(new OptionDialog.Option(R.attr.icon_intelligent_sort, "房间排序", AppApplication.getInstance().getThemeColor(R.attr.textColor1)));
            }
            options.add(new OptionDialog.Option(R.attr.icon_me_house_delete, "删除楼层", AppApplication.getInstance().getThemeColor(R.attr.secondaryColor1)));
        }
        optionDialog.setOptions(options);
        optionDialog.setListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                optionDialog.dismiss();
                OptionDialog.Option option = options.get(position);
                if(option.title.equals("修改名称")){
                    showBottomEditDialog(floorBean.getFloorName());
                }else if(option.title.equals("房间排序")){
                    gotoSortView(floorBean);
                }else if(option.title.equals("删除楼层")){
                    List<RoomBean> roomBeans = LLRoomDBManager.getInstance(getContext()).getRoomByFloorSerialNo(floorBean.getFloorSerialNo());
                    if(roomBeans != null && roomBeans.size() > 0){
                        showConfirmHintDialog(R.string.floor_has_room_delete_hint);
                    }else{
                        showConfirmCancelHintDialog(getString(R.string.delete_floor_hint, floorBean.getFloorName()));
                    }
                }else if(option.title.equals("楼层排序")){
                    gotoFLoorSortView();
                }
            }
        });
        optionDialog.popupInfo.atView = atView;
        optionDialog.show();
    }

    private void gotoSortView(FloorBean floorBean){
        Intent intent = new Intent(getContext(), RoomSrotActivity.class);
        intent.putExtra("floorSerialNo",floorBean.getFloorSerialNo());
        intent.putExtra("floorName",floorBean.getFloorName());
        startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, Intent data) {
                if (resultCode == RESULT_OK) {
                    initData();
                }
            }
        });
    }

    private void gotoFLoorSortView(){
        Intent intent = new Intent(getContext(), FloorSortActivity.class);
        startActivity(intent);
    }

    private void showBottomEditDialog(String oldText) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(getContext());
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    String newText = mBottomEditDialog.getText();
                    if(TextUtils.isEmpty(newText)){
                        toast(R.string.please_enter_floor_name);
                        return;
                    }

                    FloorBean floorBean = floors.get(tabBar.getCurrentItem() - 1);
                    Map<String, Object> data = new HashMap<>();
                    data.put("floorSerialNo", floorBean.getFloorSerialNo());
                    data.put("newName", newText);
                    LLHttpManager.editFloorName(getActivity(), data, new HttpCallback<HttpData<Void>>(null){
                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            super.onSucceed(result);
                            floorBean.setFloorName(newText);
                            LLFloorDBManager.getInstance(getContext()).put(floorBean);
                            floorTitles.set(tabBar.getCurrentItem(),newText);
                            tabBar.setTitleList(floorTitles);
                            toast(R.string.reset_success);
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }
                    });
                }
            });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setLabel(getString(R.string.floor_name));
        mBottomEditDialog.setText(oldText);
        mBottomEditDialog.setMaxLength(Constants.FLOOR_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;
    private void showConfirmHintDialog(int res){
        if(mConfirmHintDialog == null){
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity());
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setContent(res);
        mConfirmHintDialog.show();
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;
    private void showConfirmCancelHintDialog(String text){
        if(mConfirmCancelHintDialog == null){
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
            mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
                @Override
                public void onLeftClick(BaseDialog dialog) {
                    mConfirmCancelHintDialogBuilder.dismiss();
                }

                @Override
                public void onRightClick(BaseDialog dialog) {
                    mConfirmCancelHintDialogBuilder.dismiss();
                    FloorBean floorBean = floors.get(tabBar.getCurrentItem() - 1);
                    Map<String, Object> data = new HashMap<>();
                    data.put("floorSerialNo", floorBean.getFloorSerialNo());
                    LLHttpManager.deleteFloor(getActivity(), data, new HttpCallback<HttpData<Void>>(null){
                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            super.onSucceed(result);
                            LLFloorDBManager.getInstance(getContext()).remove(floorBean);
                            initData();
                            toast(R.string.delete_success);
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }
                    });
                }
            });
        }
        mConfirmCancelHintDialogBuilder.setContent(text);
        mConfirmCancelHintDialog.show();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshFloorRoomEvent(RefreshFloorRoomEvent event) {
        initData();
    }
    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return true;
    }
    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!isHidden()){
            getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
        }
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2){
            btnAdd.setVisibility(View.GONE);
        }else{
            btnAdd.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!isHidden()){
            getAttachActivity().getStatusBarConfig().statusBarDarkFont(AppApplication.getInstance().getThemeBoolean(R.attr.statusBarChangeIsDarkFont)).init();
        }
    }
}
